package club.gskj.system.service.impl;

import club.gskj.system.aliyunoss.OssEntity;
import club.gskj.system.service.AliOssService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.val;
import org.joda.time.DateTime;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class AliOssServiceImpl implements AliOssService, InitializingBean {

    @Autowired
    private OssEntity ossEntity;

    // 节点域名
    private String endPoint;
    // 公钥
    private String accessKeyId;
    // 密钥
    private String accessKeySecret;
    // 存储桶名称
    private String bucketName;


    /**
     * 在ioc容器初始化 该bean 后执行
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        endPoint = ossEntity.getEndpoint();
        accessKeyId = ossEntity.getAccessKeyId();
        accessKeySecret = ossEntity.getAccessKeySecret();
        bucketName = ossEntity.getBucketName();
    }

    /***
     *  创建 存储空间
     */
    @Override
    public void createBucket() {
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        if (ossClient.doesBucketExist(bucketName)) {
            throw new RuntimeException(bucketName + " 该存储桶已存在");
        }
        // 创建 存储桶
        ossClient.createBucket(bucketName);
        // 关闭 oss
        ossClient.shutdown();
    }

    @Override
    public String upload(MultipartFile file) {
        String uploadUrl = "";
        try {
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
                // 公共读
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            // 文件流
            InputStream inputStream = file.getInputStream();

            // 日期路径  文件夹 xxxx/yyyy/MM/dd
            String datePath = new DateTime().toString("yyyy/MM/dd");

            // 获取上传文件全名称
            String originalFilename = file.getOriginalFilename();

            // 获取UUID
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            // 获取文件扩展名
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 拼接文件名
            String newFileName = datePath + "/" + uuid + fileType;

            // 设置图片全网预览效果
            ObjectMetadata metadata = new ObjectMetadata();
            // 设置公共读
            metadata.setObjectAcl(CannedAccessControlList.PublicRead);
            metadata.setContentType(getContentType(fileType));

            // 上传
            ossClient.putObject(bucketName, newFileName, inputStream, metadata);
            ossClient.shutdown();
            // 一年不过期
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365);

            // 返回 图片路径
            uploadUrl = ossClient.generatePresignedUrl(bucketName, newFileName, expiration).toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        return uploadUrl.substring(0, uploadUrl.indexOf("?"));
    }

    @Override
    public void download(String fileName) throws IOException {

    }

    @Override
    public void listFile() {
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        ObjectListing objectListing = ossClient.listObjects(bucketName);

        for (OSSObjectSummary os : objectListing.getObjectSummaries()) {
            System.out.println("- " + os.getKey() + " (size= " + os.getSize() + ")");
        }
        ossClient.shutdown();
    }

    @Override
    public void deleteFile(String fileName) throws Exception{

        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, fileName);
        ossClient.shutdown();
    }

    public static String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }

}
